package com.educate.ucenter.shiro.filter;

import com.educate.common.web.JsonUtils;
import com.educate.common.web.R;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Log4j2
public class UserFilter extends AccessControlFilter {

    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (isLoginRequest(request, response)) {
            return true;
        } else {
            Subject subject = getSubject(request, response);
            return subject.getPrincipal() != null;
        }
    }

    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        writeResult(R.error("请先登录"), httpServletResponse);
        return false;
    }

    private void writeResult(Object result, HttpServletResponse response) throws IOException {
        byte[] value = JsonUtils.getObjectMapper().writeValueAsBytes(result);
        response.getOutputStream().write(value);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        log.debug("result:" + new String(value, "utf-8"));
    }
}
